package com.atguigu.yygh.gateway.config;

import com.atguigu.yygh.common.util.JwtHelper;
import com.google.gson.JsonObject;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @program: yygh_parent
 * @author: Mr.Zhuo
 * @create: 2022-03-21 09:58
 **/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest httpRequest = exchange.getRequest();
        HttpHeaders headers = httpRequest.getHeaders();
        List<String> token = headers.get("token");
        //获取请求路径
        String path = httpRequest.getURI().getPath();
        // 一般做判断条件的话  我们需要把错误得放在前面先处理
        if (antPathMatcher.match("/api/order/**", path)) {
            // 通过此获取
            if (token == null) {
                // token值不对
                ServerHttpResponse response = exchange.getResponse();
                return this.out(response);
            } else {
                boolean expiration = JwtHelper.isExpiration(token.get(0));
                if (expiration) {
                    // token值不对
                    ServerHttpResponse response = exchange.getResponse();
                    return this.out(response);
                }
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }


    //返回信息
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
